#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.common import check_command_injection
from hcs.gaussdb.common.const import JobType, GaussSubJobName
from hcs.gaussdb.common.gaussdb_param import JsonParam
from hcs.gaussdb.logger import log


class ResourceParam:

    def __init__(self, pid):
        self.pid = pid
        # 通过pid读取到相应的参数文件
        try:
            self._body_param = JsonParam.parse_param_with_jsonschema(self.pid)
        except Exception as err:
            raise Exception(f"Failed to parse job param file for {err}") from err
        if not self._body_param:
            raise Exception(f"Failed to parse job param file is none")

    @staticmethod
    def get_sub_job_name(param):
        sub_name = param.get("subJob", {}).get("jobName", "")
        if sub_name not in (GaussSubJobName.SUB_MOUNT, GaussSubJobName.SUB_EXEC,
                            GaussSubJobName.SUB_UMOUNT, GaussSubJobName.SUB_MERGE_DB):
            log.error(f"{sub_name} not found in sub jobs!")
            return ""
        return sub_name

    def get_param(self):
        return self._body_param

    def get_original_instance_name(self):
        """
        获取修改前原本数据库名
        """
        original_database_name = ""
        if self._body_param.get("originProtectedEnv", {}).get("name", None):
            original_database_name = self._body_param.get("originProtectedEnv").get("name")
        # 数据库名称不做校验
        return original_database_name

    def get_instance_name(self):
        instance_name = ""
        if self._body_param.get("appEnv", {}).get("name", None):
            instance_name = self._body_param.get("appEnv").get("name")
        if check_command_injection(instance_name):
            log.error("The parameter verification fails.")
            return ''
        return instance_name

    def get_register_or_change(self):
        """
        判断是注册还是修改
        """
        database_id = self._body_param.get("originProtectedEnv", {}).get("id", None)
        if not database_id:
            return JobType.REGISTER
        # 数据库名称不做校验
        return JobType.CHANGE

    def get_project_name(self):
        project_name = self._body_param.get("appEnv").get("extendInfo", {}).get("projectName", "")
        if check_command_injection(project_name):
            log.error("The parameter verification fails.")
            return ''
        return project_name

    def get_client_crt(self):
        client_crt = self._body_param.get("appEnv").get("extendInfo", {}).get("client_crt", "")
        if check_command_injection(client_crt):
            log.error("The parameter verification fails.")
            return ''
        return client_crt

    def get_project_id(self):
        project_id = self._body_param.get("appEnv").get("extendInfo", {}).get("projectId", "")
        if check_command_injection(project_id):
            log.error("The parameter verification fails.")
            return ''
        return project_id

    def get_api_addr(self):
        api_addr = self._body_param.get("appEnv").get("extendInfo", {}).get("pmAddress", "")
        if not api_addr.startswith("http"):
            log.error("The parameter verification fails.")
            return ''
        return api_addr

    def get_domain_account(self):
        belong_account = self._body_param.get("appEnv").get("extendInfo", {}).get("iamAccountName", "")
        if check_command_injection(belong_account):
            log.error("The parameter verification fails.")
            return ''
        return belong_account

    def get_business_addr(self):
        # 需要校验输入参数，仅能填IP地址，不需端口号
        business_addr = self._body_param.get("appEnv").get("extendInfo", {}).get("businessAddr", "")
        if check_command_injection(business_addr):
            log.error("The parameter verification fails.")
            return ''
        return business_addr
